package com.benmei.weike.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


public class AESUtil {
	 private static final String AESTYPE ="AES/ECB/PKCS5Padding";

	    public static String encode( String plainText,String keyStr) {
	        String ret = "";
	        byte[] encrypt = null;
	        try{
	            Key key = generateKey(keyStr);
	            Cipher cipher = Cipher.getInstance(AESTYPE);
	            cipher.init(Cipher.ENCRYPT_MODE, key);
	            encrypt = cipher.doFinal(plainText.getBytes());
	        }catch(Exception e){
	            e.printStackTrace();
	        }
	        try {
	            ret = new String(Base64.encodeBase64(encrypt));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return ret;
	    }

	    public static String decode(String decryptData, String keyStr) {
	        String ret = "";
	        byte[] decryptResult = null;
	        try {
	            byte[] decyptBody = Base64.decodeBase64(decryptData);
	            Key key = generateKey(keyStr);
	            Cipher cipher = Cipher.getInstance(AESTYPE);
	            cipher.init(Cipher.DECRYPT_MODE, key);
	            decryptResult = cipher.doFinal(decyptBody);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        if(null!=decryptResult){
	            ret = new String(decryptResult).trim();
	        }
	        return ret;
	    }

	    private static Key generateKey(String key)throws Exception{
	        try{
	            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
	            return keySpec;
	        }catch(Exception e){
	            e.printStackTrace();
	            throw e;
	        }

	    }
	    /** 
	     * 使用指定的字符串生成秘钥 
	     */  
	    public static String getKeyByPass(String loginName){  
	        //生成秘钥  
	        String secretKey=null;
	        try {    
	            KeyGenerator kg = KeyGenerator.getInstance("AES");    
	           // kg.init(128);//要生成多少位，只需要修改这里即可128, 192或256    
	            //SecureRandom是生成安全随机数序列，password.getBytes()是种子，只要种子相同，序列就一样，所以生成的秘钥就一样。  
	            kg.init(128, new SecureRandom(loginName.getBytes()));  
	            SecretKey sk = kg.generateKey();    
	            byte[] b = sk.getEncoded();    
	            secretKey= byteToHexString(b);    
	            System.out.println(secretKey);    
	            System.out.println("十六进制密钥长度为"+loginName.length());    
	            System.out.println("二进制密钥的长度为"+loginName.length()*4);    
	        } catch (NoSuchAlgorithmException e) {    
	            e.printStackTrace();    
	            System.out.println("没有此算法。");    
	        }  
	        return secretKey;
	    }  
	    /** 
	     * byte数组转化为16进制字符串 
	     * @param bytes 
	     * @return 
	     */  
	    public static String byteToHexString(byte[] bytes){       
	        StringBuffer sb = new StringBuffer();       
	        for (int i = 0; i < bytes.length; i++) {       
	             String strHex=Integer.toHexString(bytes[i]);   
	             if(strHex.length() > 3){       
	                    sb.append(strHex.substring(6));       
	             } else {    
	                  if(strHex.length() < 2){    
	                     sb.append("0" + strHex);    
	                  } else {    
	                     sb.append(strHex);       
	                  }       
	             }    
	        }    
	       return  sb.toString();       
	    } 
	    
	    public static void main(String[] args) {
	      String keyStr = "UITN25LMUQC436IM";
	      // String content = "{\"area_city\":\"杭州\",\"hear_money\":\"50万到100万\",\"other_phone\":\"12345678912\",\"cmobile\":\"13758154074\",\"clientflag\":\"locan_submit\",\"exCode\":\"crm_reg\"}";
	       String content="{\"rspCode\":\"000000\",\"policyId\":1,\"rspMsg\":\"成功\",\"xb_reqreflex\":\"MsgAppPolicyInfo\"}";    
	       System.out.println("加密前：" + content);
	            String xx = encode(content, keyStr);
	        System.out.println("加密：" + xx);
	       // String sss = "H7hpIdakzJm0kkAtLs6qopqb7u8cpdPMKNMtR82JL4O%2Fn1gblgI1giWGnUnLFnf34c7WHMxhVOonI4vT3NPXEVr5uYyu%2Bsbjun7pNV%2BLlIMVvFkLHx0TaEA9wZ40lWZJW1r7dlXZxQf6JyvuOt%2FUSw5sPX7KMESLmj%2BU81obgZp24znjkbZaZQV5hFpS8D4l9sq2cSzDOFzzh%2FkUf8sRYTCyCAHJwanLuphLMUZ62L4bE6BEaDUntursj1JNdn%2Fb%2BZwXZtDzCXyBta0WOAHEIu1MLVBZaNOxHV7396sOqtATSnPckMs2VZdWhB04%2BLV5oRF5OFaae5dOIH3Atjf5azHAL3XQJWwvpSCMhDuWu%2B513jRcRBisDv9AFIfOEQ%2FWX6LjMoSqNPf0%2B0EHz5EHVg%3D%3D";
	        String decString = decode("EdWTGfwobxSfU96Sge2NHc1l0OKhw2tcRgXXeT9f+MjZiSHSbcY6kk+FpFur7jgaxJdl0IWMB0Hq\r\niOQiU9YcUmvC8lkJkVfmuf5oKd+y8yA=",keyStr);

	        System.out.println("解密："+decString);

	    }


}
